package cc.linker.steplink.crm.service.impl;

import cc.linker.steplink.crm.service.EmailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.mail.internet.MimeMessage;

/**
 * @Description: 邮箱服务
 * @Author: yhb
 * @Date: Created in 2021/5/26 11:06
 * @Version:1.0
 */
@Service
@Slf4j
public class EmailServiceImpl implements EmailService {

    @Autowired
    private JavaMailSender javaMailSender;

    //这一步是获取application.properties中设置的发件人邮箱地址
    @Value("${spring.mail.username}")
    private String username;


    @Override
    @Async("emailExecutor")
    public void sendEmailToAddress(String email, String content, String taskName) throws Exception {
        LOGGER.info("开始发送邮箱{}", email);
        //发邮件
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        // 第二个参数true表示使用HTML语言来编写邮件
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
        //发件人邮件地址(上面获取到的，也可以直接填写,string类型)
        helper.setFrom(username);
        //抄送自己
        helper.setCc(username);
        //邮件主题
        helper.setSubject(taskName);
        //邮件正文
        helper.setText(content, true);
        //收件人邮件地址
        helper.setTo(email);
        javaMailSender.send(mimeMessage);
        LOGGER.info("邮件发送给{}完成", email);
    }
}
